package com.wen.mall.controller;

import com.wen.mall.consts.Mallconst;
import com.wen.mall.form.UserLoginForm;
import com.wen.mall.form.UserRegisterForm;
import com.wen.mall.pojo.User;
import com.wen.mall.service.UserService;
import com.wen.mall.vo.ResponseVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author 温嘉璐
 */
@Controller

@Slf4j
@ResponseBody
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 注册
     *
     * @param userRegisterForm
     * @param bindingResult
     * @return
     */
    @PostMapping("/user/register")
    @ApiOperation("注册")

    public ResponseVo register(@Valid @RequestBody UserRegisterForm userRegisterForm) {

        User user = new User();
        //将userform的内容copy到user
        BeanUtils.copyProperties(userRegisterForm, user);
        return userService.register(user);
    }

    @PostMapping("/user/login")
    @ApiOperation("登录")

    public ResponseVo login(@Valid  @RequestBody UserLoginForm userLoginForm, HttpSession session) {

        User user = new User();
        BeanUtils.copyProperties(userLoginForm, user);
        ResponseVo<User> login = userService.login(user);
        session.setAttribute(Mallconst.CURRENT_USER, login.getData());
        return login;
    }

    @GetMapping("/user")
    @ApiOperation("获取用户信息")
    public ResponseVo<User> get(HttpSession session) {
        //session保存在内存里，改进版本 token+redis
        User user = (User) session.getAttribute(Mallconst.CURRENT_USER);


        return ResponseVo.success(user);
    }
    @PostMapping("/user/logout")
    @ApiOperation("退出")
    public ResponseVo<User> logout(HttpSession session){
        session.removeAttribute(Mallconst.CURRENT_USER);
        return ResponseVo.success();
    }

}
